package com.yeban.javase.day19;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * @Desc TODO
 * @Author yeban
 * @Date 2025/11/3
 */
public class TCPServer {

    public static void main(String[] args) {
        System.out.println("---------- TCPServer ----------");
        Scanner sc = new Scanner(System.in);
        ServerSocket ss = null;
        BufferedReader br = null;
        Socket socket = null;
        PrintWriter out = null;

        try {
            // 启动服务端
            ss = new ServerSocket(8123);
            // 等待接入客户端
            socket = ss.accept();
            System.out.println("成功接入客户端：" + socket.getRemoteSocketAddress());

            // 将客户端的socket传入的InputStream流用BufferedReader接收
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String str = null;
            // 读消息：循环读消息，客户端发exit后，那边不发消息，str为空退出循环
            while((str = br.readLine()) != null) {
                if(str.equals("exit")) {
                    System.out.println(socket.getRemoteSocketAddress() + "下班了！");
                } else {
                    System.out.println(socket.getRemoteSocketAddress() + "说：" + str);
                }

                // 写消息
                String s = sc.nextLine();
                // 输入exit退出服务端
                if(s.equals("exit")) {
                    break;
                }
                out = new PrintWriter(socket.getOutputStream());
                out.println(s);
                out.flush();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            // 先打开，后关闭
            // 关闭PrintWriter 的 out
            if(out != null) {
                out.close();
            }
            // 关闭BufferedReader 的 br
            if(br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            // 关闭Socket 的 socket
            if(socket != null) {
                out.close();
            }
            // 关闭ServerSocket 的 ss
            if(ss != null) {
                try {
                    ss.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

        }
    }
}
